package com.qf.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qf.commons.TableData;
import com.qf.entity.User;
import com.qf.exception.BizException;
import com.qf.mapper.UserDao;
import com.qf.service.UserService;
import com.qf.utils.DateUtils;
import com.qf.utils.ExportExcel;
import com.qf.utils.ImportExcel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Elasticsearch
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

//    @Value("${imageServer}")
//    private String imageServer;

    @Value("${excelPath}")
    private String excelPath;

//    @Value("${excelTempDir}")
//    private String excelTempDir;

    private UserDao userDao;

    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public TableData<User> getPageData(Integer offset, Integer limit, String name, String sex,  Integer status,
                                       String email, Date afterDate,
                                       Date endDate) throws BizException {
        TableData<User> tableData = new TableData();
        try {
            Page<User> page = PageHelper.offsetPage(offset, limit);
            List<User> userList  = userDao.dynamicQuery(name,sex,status,email,
                    afterDate,endDate);
            tableData.setTotal(page.getTotal());
            tableData.setRows(userList);
        }catch (Exception ex) {
            throw new BizException("业务层层异常: " + ex.getMessage());
        }
        return tableData;
    }

    @Override
    public void deleteUserById(Integer id) throws BizException {
        try {
            userDao.deleteById(id);
        }catch (Exception ex) {
            throw new BizException("业务层删除异常: " + ex.getMessage());
        }
    }

    @Override
    public User getUserById(Integer id) throws BizException {
        User user = null;
        try {
            user = userDao.selectById(id);
            user.setAvatar( user.getAvatar());  // http://localhost/5677yyufe.jpg
//            Integer.parseInt("ab");
        }catch (Exception ex) {
            ex.printStackTrace();
            throw new BizException("业务层查询异常: " + ex.getMessage());
        }
        return user;
    }

    @Override
    public void updateUser(User user) throws BizException{
        try {
            userDao.updateById(user);
        }catch (Exception ex) {
            ex.printStackTrace();
            throw new BizException("业务层更新异常: " + ex.getMessage());
        }
    }

    @Override
    public String generateExcel(String fileName,String name, String sex, Integer status,String email,
                                Date afterDate, Date endDate) throws BizException{

        String fullPath = null;
        try {
            List<User> allUsers = userDao.dynamicQuery(name,sex,status,email,
                    afterDate,endDate);

            String title = "用户信息";
            String[] rowNames = {"ID", "姓名", "邮件", "性别", "电话", "状态", "余额", "注册时间"};

            List<Object[]> userObjs = new ArrayList<>();

            allUsers.forEach(u -> {
                if (u.getRegisterDate()==null){
                    u.setRegisterDate(new Date());
                }
                Object[] obj = {
                        u.getId(),
                        u.getName(),
                        u.getEmail(),
                        "M".equals(u.getSex()) ? "男" : "女",
                        u.getPhone(),
                        1 == u.getStatus() ? "可用" : "不可用",
                        u.getBalance(),
                        DateUtils.transferDateToStr(u.getRegisterDate(), DateUtils.DATE_24FULL_STR)
                };
                userObjs.add(obj);
            });

            ExportExcel exportExcel = new ExportExcel(title, rowNames, userObjs);

            //根据时间生成文件名  20200630164834.xls
//            String fileName = DateUtils.transferDateToStr(new Date(), DateUtils.DATE_KEY_STR) + ".xls";
            fullPath = excelPath + fileName;

            exportExcel.export(fullPath);
        }catch (Exception ex) {
            ex.printStackTrace();
            throw new BizException("业务层生成Excel异常: " + ex.getMessage());
        }
        return fullPath;
    }

    /**
     * mybatis上百万数据插入： 1.代码拆分excel，20份 (数据如果出错不好排查、内存), 存储文件名。
     *                       2.单份文件上传，失败的文件，让用户下载，让用户再次上传。
     */
    @Override
    public Integer parseExcelAndInsertData(InputStream inputStream) throws BizException {
        ImportExcel importExcel = new ImportExcel();

        List<Object[]> list = importExcel.readExcelContent(inputStream);  //解析数据
        list.remove(0);
        list.remove(0);
        List<User> userList = new ArrayList<>();

        for(Object[] objects : list) {
            User user = new User();

            user.setName(objects[1].toString());
            user.setEmail(objects[2].toString());
            user.setSex("男".equals(objects[3].toString()) ? "M" : "F");
            user.setPhone(objects[4].toString());
            user.setStatus("可用".equals(objects[5].toString()) ? 1 : 0);
            user.setBalance(BigDecimal.valueOf(Double.parseDouble(objects[6].toString())));
            if (null!=objects[7].toString()){

                try {
                    user.setRegisterDate(DateUtils.strToDate(objects[7].toString(),
                            DateUtils.DATE_SMALL_STR));
                } catch (Exception e) {
                    e.printStackTrace();
                    user.setRegisterDate(DateUtils.strToDate(objects[7].toString(),DateUtils.DATE_24FULL_STR));
                }
            }


            user.setPassword("qianfeng123");
            userList.add(user);
        }
        int num = 0;
        if(userList.size() > 0) {
            num = userDao.batchInsertUsers(userList);
            System.out.println(num);
        }
        return num;
    }
}
